import { IMainApi, IUser, IUserUpdate } from '../interfaces'

class MainApi implements IMainApi {
  _url: string

  constructor(options: any) {
    this._url = options.url;
  }

  private _checkResponse = (res: any) => {
    if (res.ok) {
      return res.json();
    }
    return Promise.reject(`Ой...: ${res.status}`);
  }

  private async _fetch(path: string, method: string, data?: any) {
    let body = data;
    if ((method === 'PATCH' || method === 'POST') && data) {
      body = JSON.stringify(data);
    }

    return fetch(this._url + path, {
      method,
      headers: {
        authorization: `Bearer ${localStorage.getItem('jwt')}`,
        'Content-Type': 'application/json',
      },
      body,
    }).then(this._checkResponse);
  }

  getUserInfo():Promise<any> {
    return this._fetch('/users/me', 'GET');
  }

  setUserInfo(data: IUserUpdate) {
    return this._fetch('/users/me', 'PATCH', data);
  }

  // addNewCard(data) {
  //   return this._fetch('/movies', 'POST', data);
  // }
  //
  // getInitialCards() {
  //   return this._fetch('/movies', 'GET');
  // }
  //
  // deleteCard(id) {
  //   return this._fetch(`/movies/${id}`, 'DELETE');
  // }
}

export const mainApi = new MainApi({
  // url: `https://api.movies-diplom.nomoredomainsicu.ru`,
  url: `http://localhost:3000`,
});
